package com.tcjk.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.tcjk.dao.AccessTokenDao;
import com.tcjk.entity.AccessToken;
import com.tcjk.po.JsapiTicket;
import com.tcjk.po.MenuBean;
import com.tcjk.po.WebAccessToken;
import com.tcjk.service.WxInterService;
import com.tcjk.utils.Const;
import com.tcjk.utils.HttpUtil;
import com.tcjk.utils.TestGetPost;

@Service
public class WxInterServiceImpl implements WxInterService {
	@Autowired
	AccessTokenDao accessTokenDao;

	@Override
	public AccessToken getAccessToken() {
		AccessToken accessToken = null;
		boolean invalid = true;
		accessToken = accessTokenDao.findByProperty("_id", 1);
		if (null != accessToken) {
			Date saveTime = accessToken.getSaveTime();
			long currentTimeMilli = System.currentTimeMillis();
			if (((currentTimeMilli - saveTime.getTime()) / 1000) > accessToken.getExpires_in()) {
				invalid = false;
			}
		}else{
			invalid = false;
			accessToken = new AccessToken();
			accessToken.set_id(1);
			accessToken.setSaveTime(new Date());
			accessTokenDao.save(accessToken);
			accessToken = accessTokenDao.findByProperty("_id", 1);
		}
		System.out.println("Invalid=="+invalid);
		if (!invalid) {
			// 失效
			String url = "https://api.weixin.qq.com/cgi-bin/token";
			String param = "grant_type=client_credential&appid=" + Const.wx_appid + "&secret=" + Const.wx_secret;
//			System.out.println("url="+url);
//			System.out.println("param="+param);
			String result = TestGetPost.sendGet(url, param);
			System.out.println("result=" + result);
			Gson gson = new Gson();
			AccessToken json = gson.fromJson(result, AccessToken.class);
			accessToken.setAccess_token(json.getAccess_token());
			accessToken.setErrcode(json.getErrcode());
			accessToken.setErrmsg(json.getErrmsg());
			accessToken.setExpires_in(json.getExpires_in()-10);
			accessToken.setSaveTime(new Date());
			accessTokenDao.update(accessToken);
		}
		return accessToken;
	}

	@Override
	public void downFile(String accessToken, String MEDIA_ID, String path) throws IOException {
		StringBuffer urlBuf = new StringBuffer();
		urlBuf.append("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=").append(accessToken).append("&media_id=").append(MEDIA_ID);
		HttpUtil.downloadFile(path, urlBuf.toString());
	}

	@Override
	public JsapiTicket getJsapiTicket(String ACCESS_TOKEN) {
		JsapiTicket jt = null;
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
		String param = "access_token="+ACCESS_TOKEN+"&type=jsapi";
		String result = TestGetPost.sendGet(url, param);
	//	System.out.println("result="+result);
		Gson gson = new Gson();
		jt = gson.fromJson(result, JsapiTicket.class);
		return jt;
	}

	@Override
	public WebAccessToken getWebAccessToken(String code) {
		WebAccessToken wat = null;
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		String param = "appid="+Const.wx_appid+"&secret="+Const.wx_secret+"&code="+code+"&grant_type=authorization_code";
		String result = TestGetPost.sendGet(url, param);
		System.out.println("result="+result);
		Gson gson = new Gson();
		wat = gson.fromJson(result, WebAccessToken.class);
		return wat;
	}

	@Override
	public void menuCreat() {
		String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+getAccessToken().getAccess_token();
		
		MenuBean homePage = new MenuBean();
		homePage.setName("首页");
		homePage.setType("view");
		homePage.setUrl("http://www.baidu.com");
		homePage.setKey("v100021");

		
		MenuBean product = new MenuBean();
		product.setName("商品展示");
		product.setType("view");
		product.setUrl("http://www.baidu.com");
		product.setKey("v100022");
		
		MenuBean aboutUs = new MenuBean();
		aboutUs.setName("关于我们");
		aboutUs.setType("view");
		aboutUs.setUrl("http://www.baidu.com");
		aboutUs.setKey("v100023");
		
		List<MenuBean> sbMb = new ArrayList<MenuBean>();
		sbMb.add(homePage);
		sbMb.add(product);
		sbMb.add(aboutUs);
		
		MenuBean xinchenInfo = new MenuBean();
		xinchenInfo.setName("首页");
		xinchenInfo.setType("view");
		xinchenInfo.setUrl("http://120.78.136.43/tcjk/wx/main");
		xinchenInfo.setKey("v10002");
	//	xinchenInfo.setSub_button(sbMb);

//		MenuBean serve = new MenuBean();
//		serve.setName("服务中心");
//		serve.setType("view");
//		serve.setUrl("");
//		serve.setKey("v10003");

		MenuBean mb = new MenuBean();
		mb.setName("个人中心");
		mb.setType("view");
	//	mb.setUrl("http://www.helpdoctor.cn/tcjk/wx/index");
		mb.setUrl("http://120.78.136.43/tcjk/wx/index");
	//	mb.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Const.wx_appid+"&redirect_uri=http%3A%2F%2Fwww.cool-star.cn%2FZnWatch%2FWeiXinApp%21mainIndex.action&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
		mb.setKey("v10001");
		
		HashMap<String,List<MenuBean>> map = new HashMap<String,List<MenuBean>>();
		List<MenuBean> list = new ArrayList<MenuBean>();
		list.add(xinchenInfo);
	//	list.add(serve);
		list.add(mb);
		
		map.put("button", list);
		JSONObject  object = new JSONObject(map);
		String json = object.toString();
		String result = TestGetPost.sendPost(url, json);
		System.out.println("result="+result);
	}
}